package delegate4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.FutureTask;

public class AsyncResult<TResult> {

    private List<FutureTask<TResult>> tasks;

    public AsyncResult(List<FutureTask<TResult>> tasks) {
        this.tasks = tasks;
    }

    public TResult getResult() {
        TResult result = null;

        //注：此处需要使用for循环以保证result的值为最后一个委托的返回值
        for (int i = 0; i < tasks.size(); i++) {
            FutureTask<TResult> task = tasks.get(i);
            try {
                result = task.get();
            } catch (Exception e) {
                result = null;
            }
        }
        return result;
    }

    public void cancel() {
        for (FutureTask<TResult> task : tasks) {
            task.cancel(true);
        }
    }

    public boolean isDone() {
        boolean isFinish = true;
        for (FutureTask<TResult> task : tasks) {
            if (!task.isDone()) {
                isFinish = false;
                break;
            }
        }
        return isFinish;
    }

    public List<FutureTask<TResult>> getTasks() {
        return new ArrayList<>(tasks);
    }

}
